package api

import (
	"GopherFocus/app/model"
	"GopherFocus/app/system/index/internal/define"
	"GopherFocus/app/system/index/internal/service"
	"GopherFocus/library/response"
	"github.com/gogf/gf/net/ghttp"
)

var Content = contentApi{}

type contentApi struct{}

// 创建内容页面
func (a *contentApi) Create(r *ghttp.Request) {
	// 必须传入一个类型参数
	var (
		req *define.ContentCreateReq
	)
	if err := r.Parse(&req); err != nil {
		service.View.Render500(r, model.View{
			Error: err.Error(),
		})
	} else {
		service.View.Render(r, model.View{
			ContentType: req.Type,
		})
	}
}

// 创建内容接口，不需要渲染页面(渲染页面有Create接口)
// ParseForm()解析表单数据
func (a *contentApi) DoCreate(r *ghttp.Request) {
	var (
		req *define.ContentDoCreateReq
	)
	if err := r.ParseForm(&req); err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	if data, err := service.Content.Create(r.Context(), req.ContentCreateInput); err != nil {
		response.JsonExit(r, 1, err.Error())
	} else {
		response.JsonExit(r, 0, "", data)
	}
}

// 修改内容页面
func (a *contentApi) Update(r *ghttp.Request) {
	var (
		req *define.ContentUpdateReq
	)
	if err := r.Parse(&req); err != nil {
		service.View.Render500(r, model.View{
			Error: err.Error(),
		})
	}
	if data, err := service.Content.GetDetail(r.Context(), req.Id); err != nil {
		service.View.Render500(r, model.View{
			Error: err.Error(),
		})
	} else {
		service.View.Render(r, model.View{
			ContentType: data.Content.Type,
			Data:        data,
		})
	}
}

// 修改内容接口，不需要渲染页面
func (a *contentApi) DoUpdate(r *ghttp.Request) {
	var (
		req *define.ContentDoUpdateReq
	)
	if err := r.ParseForm(&req); err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	if err := service.Content.Update(r.Context(), req.ContentUpdateInput); err != nil {
		response.JsonExit(r, 1, err.Error())
	} else {
		response.JsonExit(r, 0, "")
	}
}

// 删除内容接口，不需要渲染页面
func (a *contentApi) DoDelete(r *ghttp.Request) {
	var (
		req *define.ContentDoDeleteReq
	)
	if err := r.ParseForm(&req); err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	if err := service.Content.Delete(r.Context(), req.Id); err != nil {
		response.JsonExit(r, 1, err.Error())
	} else {
		response.JsonExit(r, 0, "")
	}
}

// 采纳回复
func (a *contentApi) AdoptReply(r *ghttp.Request) {
	var (
		req *define.ContentAdoptReplyReq
	)
	if err := r.ParseForm(&req); err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	if err := service.Content.AdoptReply(r.Context(), req.Id, req.ReplyId); err != nil {
		response.JsonExit(r, 1, err.Error())
	} else {
		response.JsonExit(r, 0, "")
	}
}
